import Vue from 'vue';
import Vuex from 'vuex';
import router, { constantRoutes } from '@/router';
import { getTopList, getRouters } from '@/api';
// 匹配views里面所有的.vue文件
// const modules = import.meta.glob('./../../views/**/*.vue');

Vue.use(Vuex)

export default new Vuex.Store({
	modules: {},
	state: {
		userInfo: {},
		deviceWidth: null,
		workTitle: '',
		topList: [], // 右侧图片列表
		addRoutes: [], // 动态路由
		routes: [], // 全路由(静态+动态)
		sidebarRouters: [], // 导航路由(包含401 404)
		defaultRoutes: [],
		topbarRouters: [],

		areaGroup: [],
		familyGroup: [],
		styleGroup: [],
		typeGroup: [],
		yearGroup: [],
		cityGroup: [],
		groupTopHeight: 0
	},
	getters: {
		deviceWidth: state => state.deviceWidth,

		sidebarRouters: state => state.sidebarRouters,
		defaultRoutes: state => state.defaultRoutes,
		topbarRouters: state => state.topbarRouters,

		topList: state => state.topList,
		areaGroup: state => state.areaGroup,
		familyGroup: state => state.familyGroup,
		styleGroup: state => state.styleGroup,
		typeGroup: state => state.typeGroup,
		cityGroup: state => state.cityGroup,
		groupTopHeight: state => state.groupTopHeight,

		// min-width 大于等于 (定义输出设备中的页面最小可见区域宽度)
		// max-width 小于     (定义输出设备中的页面最大可见区域宽度)

		/* 当屏幕尺寸小于750px时，应用下面的CSS样式 */
		// @media screen and (max-width: 750px) {
		//   .class {
		//     background: #ccc;
		//   }
		// }
		/* 当屏幕尺寸大于等于1200px时，应用下面的CSS样式 */
		// @media screen and (min-width: 1200px) {
		//   .class {
		//     background: #ccc;
		//   }
		// }

		// 设备宽度小于等于750 为移动端 否则 pc端
		deviceMode: state => {
			if (!state.deviceWidth) return;
			return state.deviceWidth <= 750 ? "m" : "pc";
		},
		// 设备宽度<1200 为移动端(手机或平板) 否则 pc端
		devicePdMode: state => {
			if (!state.deviceWidth) return;
			return state.deviceWidth < 1200 ? "mp" : "pc";
		},
		// 750<=设备宽度<1200 为平板
		deviceIpadMode: state => {
			if (!state.deviceWidth) return;
			return state.deviceWidth >= 750 && state.deviceWidth < 1200;
		}
	},
	mutations: {
		USERINFO(state, userInfo) {
			state.userInfo = userInfo;
		},
		UPDATE_DEVICEWIDTH(state, deviceWidth) {
			state.deviceWidth = deviceWidth;
		},
		UPDATE_WORKTITLE(state, workTitle) {
			state.workTitle = workTitle;
		},
		SET_TOPLIST(state, topList) {
			state.topList = topList;
		},
		SET_ROUTES: (state, routes) => {
			state.addRoutes = routes
			state.routes = constantRoutes.concat(routes)
		},
		SET_SIDEBAR_ROUTERS: (state, routes) => {
			state.sidebarRouters = routes
		},
		SET_DEFAULT_ROUTES: (state, routes) => {
			state.defaultRoutes = constantRoutes.concat(routes)
		},
		SET_TOPBAR_ROUTES: (state, routes) => {
			state.topbarRouters = routes
		},
		SET_AREA_GROUP: (state, areaGroup) => {
			state.areaGroup = areaGroup
		},
		SET_FAMILY_GROUP: (state, familyGroup) => {
			state.familyGroup = familyGroup
		},
		SET_STYLE_GROUP: (state, styleGroup) => {
			state.styleGroup = styleGroup
		},
		SET_TYPE_GROUP: (state, typeGroup) => {
			state.typeGroup = typeGroup
		},
		SET_YEAR_GROUP: (state, yearGroup) => {
			state.yearGroup = yearGroup
		},
		SET_CITY_GROUP: (state, cityGroup) => {
			state.cityGroup = cityGroup
		},
		SET_TOP_HEIGHT: (state, groupTopHeight) => {
			state.groupTopHeight = groupTopHeight
		}
	},
	actions: {
		getTopImgList({ commit }) {
			return new Promise((resolve, reject) => {
				getTopList().then(res => {
					const { data = [] } = res;
					commit('SET_TOPLIST', data);
					resolve(data);
				}).catch(err => {
					reject(err);
				})
			})
		},
		generateRoutes({ commit }, roles) {
			return new Promise(resolve => {
				getRouters().then(res => {
					console.log('routes-', res);
					if(res.code == 200) {
						const sdata = JSON.parse(JSON.stringify(res.data));
						const rdata = JSON.parse(JSON.stringify(res.data));

						const sidebarRoutes = filterAsyncRouter(sdata); // 左侧导航路由
						console.log('sidebarRoutes-', sidebarRoutes);

						// const rewriteRoutes = filterAsyncRouter(rdata, false, true); // 重写路由
						// rewriteRoutes.push({ path: '*', redirect: '/404', hidden: true });

						commit('SET_ROUTES', sidebarRoutes);
						commit('SET_SIDEBAR_ROUTERS', constantRoutes.concat(sidebarRoutes));
						commit('SET_DEFAULT_ROUTES', sidebarRoutes);

						const frRoutes = filterRoute(rdata);
						console.log('frRoutes-', frRoutes);
						commit('SET_TOPBAR_ROUTES', frRoutes);
						resolve(sidebarRoutes);
					}
				})
			})
		}
	}
})

/**
 * 遍历后台传来的路由对象，转换为组件对象
 * @param asyncRouterMap 后台传来的路由字符串
 * @param lastRouter 上一级路由
 * @param type 是否是重写路由
 */
const filterAsyncRouter = (asyncRouterMap, lastRouter = false, type = false) => {
	const arr = asyncRouterMap.filter((route, index) => {
		if (type && route.children) {
			route.children = filterChildren(route.children)
		}
		if(route.query) {
			route.query = JSON.parse(route.query);
		}
		if (route.component) {
			// Layout ParentView 组件特殊处理
			if (route.component === 'Layout') {
				route.component = () => import('@/components/layout/BasicLayout.vue');
				if(index === 0) {
					route.redirect = { path: "/works" };
					route.path = '/';
				}
			} else if (route.component === 'ParentView') {
				route.component = ParentView
			} else if (route.component === 'InnerLink') {
				route.component = InnerLink
			} else {
				route.component = loadView(route.component)
			}
		}
		if (route.children != null && route.children && route.children.length) {
			route.children = filterAsyncRouter(route.children, route, type)
		} else {
			delete route['children']
			delete route['redirect']
		}
		return true
	});
	return arr;
}

const filterRoute = (asyncRouterMap) => {
	return asyncRouterMap.filter((route, index) => {
		if(route.query) {
			route.query = JSON.parse(route.query);
		}
		if (route.component) {
			// Layout ParentView 组件特殊处理
			if (route.component === 'Layout') {
				route.component = () => import('@/components/layout/BasicLayout.vue');
				if(index === 0) {
					route.redirect = { path: "/works" };
					route.path = '/';
				}
			} else if (route.component === 'ParentView') {
				route.component = ParentView
			} else if (route.component === 'InnerLink') {
				route.component = InnerLink
			} else {
				route.component = loadView(route.component)
			}
		}
		if (route.children && route.children.length) {
			route.children = filterRoute(route.children)
		} else {
			delete route['children']
			delete route['redirect']
		}
		return !route.hidden;
	});
}

const filterChildren = (childrenMap, lastRouter = false) => {
	let children = []
	childrenMap.forEach((el, index) => {
		if (el.children && el.children.length) {
			if (el.component === 'ParentView' && !lastRouter) {
				el.children.forEach(c => {
					c.path = el.path + '/' + c.path
					if (c.children && c.children.length) {
						children = children.concat(filterChildren(c.children, c))
						return
					}
					children.push(c)
				})
				return
			}
		}
		if (lastRouter) {
			el.path = lastRouter.path + '/' + el.path
			if (el.children && el.children.length) {
				children = children.concat(filterChildren(el.children, el))
				return
			}
		}
		children = children.concat(el)
	})
	return children
}

const loadView = (view) => {
	return () => import(`@/views/${view}`)
	// if (process.env.NODE_ENV === 'development') {
	// 	return (resolve) => require([`@/views/${view}`], resolve)
	// } else {
	// 	// 使用 import 实现生产环境的路由懒加载
	// 	return () => import(`@/views/${view}`)
	// }
}

export const loadView2 = (view) => {
	let res;
	for (const path in modules) {
		const dir = path.split('views/')[1].split('.vue')[0];
		if (dir === view) {
			res = () => modules[path]();
		}
	}
	return res;
};